# PowerShell脚本用于初始化WVP数据库

Write-Host "正在初始化WVP数据库..." -ForegroundColor Green

# 数据库连接参数
$server = "127.0.0.1"
$port = "3306"
$username = "root"
$password = "12345678"
$database = "wvp"

# 创建缺失表的SQL
$createRecordPlanTable = @"
CREATE TABLE IF NOT EXISTS wvp_record_plan (
    id INT AUTO_INCREMENT PRIMARY KEY,
    snap TINYINT(1) DEFAULT 0,
    name VARCHAR(255) NOT NULL,
    create_time VARCHAR(50),
    update_time VARCHAR(50)
);
"@

$createRecordPlanItemTable = @"
CREATE TABLE IF NOT EXISTS wvp_record_plan_item (
    id INT AUTO_INCREMENT PRIMARY KEY,
    start INT,
    stop INT,
    week_day INT,
    plan_id INT,
    create_time VARCHAR(50),
    update_time VARCHAR(50)
);
"@

try {
    # 尝试使用.NET MySQL连接器
    Add-Type -AssemblyName System.Data
    
    # 构建连接字符串
    $connectionString = "Server=$server;Port=$port;Database=$database;Uid=$username;Pwd=$password;"
    
    Write-Host "尝试连接到数据库..." -ForegroundColor Yellow
    
    # 这里我们使用一个简单的方法：创建SQL文件并提示用户手动执行
    $sqlContent = @"
USE $database;

$createRecordPlanTable

$createRecordPlanItemTable

-- 检查表是否创建成功
SHOW TABLES LIKE 'wvp_record_plan%';
"@

    # 将SQL保存到文件
    $sqlFile = "create_tables.sql"
    $sqlContent | Out-File -FilePath $sqlFile -Encoding UTF8
    
    Write-Host "SQL脚本已生成: $sqlFile" -ForegroundColor Green
    Write-Host "请手动执行以下命令来创建数据库表:" -ForegroundColor Yellow
    Write-Host "mysql -h $server -P $port -u $username -p$password < $sqlFile" -ForegroundColor Cyan
    
} catch {
    Write-Host "脚本执行失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "请手动执行SQL脚本创建数据库表" -ForegroundColor Yellow
}

Write-Host "按任意键继续..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
